package com.xzwzz.kotlindemo

import com.alibaba.fastjson.JSONArray
import com.xzwzz.kotlindemo.city.CityBean
import com.xzwzz.kotlindemo.city.categoryUtil
import java.util.Scanner
import java.io.IOException
import java.io.InputStreamReader
import java.io.BufferedReader
import java.io.FileInputStream


object FindCityUtil {

    var result: List<List<String>>? = null

    var city1No = mutableMapOf<String, String>()
    var city2No = mutableMapOf<String, String>()
    @Throws(IOException::class)
    @JvmStatic
    fun main(args: Array<String>) {
        while (true) {
            println()
            println("请输入路径")
            val scanner = Scanner(System.`in`)
            val path = scanner.nextLine()
            //            ExcelSplitUtil.calcuExcel(path);//计算数量
//            ExcelSplitUtil.FindCityUtil(path, true)//拆分表
            val citys = JSONArray.parseArray(
                readFile("/Users/xzwzz/WorkFolder/KotlinDemo/src/com/xzwzz/kotlindemo/city.json"),
                CityBean::class.java
            )


            val r = citys.groupBy { it.level }["3"]!!
            citys.forEach {
                if (!city1No.containsKey(it.shortname)) {
                    city1No.put(it.name, it.pid)
                }
                if (!city2No.containsKey(it.shortname)) {
                    city2No.put(it.name, it.id)
                }
            }
            categoryUtil.execute(path, false, getRegexString(r));

        }
    }

    fun getRegexString(r: List<CityBean>): String {
        var stringBuffer = StringBuffer()

        stringBuffer.append("[")

        r.forEach {

            if (it.shortname.trim().length != 0) {
                stringBuffer.append("${it.shortname}|")
            }
        }

        stringBuffer = StringBuffer(stringBuffer.substring(0, stringBuffer.length - 1))

        stringBuffer.append("]")
        return stringBuffer.toString()
    }

    @Throws(IOException::class)
    fun readToBuffer(buffer: StringBuffer, filePath: String) {
        val `is` = FileInputStream(filePath)
        var line: String? // 用来保存每行读取的内容
        val reader = BufferedReader(InputStreamReader(`is`))
        line = reader.readLine() // 读取第一行
        while (line != null) { // 如果 line 为空说明读完了
            buffer.append(line) // 将读到的内容添加到 buffer 中
            buffer.append("\n") // 添加换行符
            line = reader.readLine() // 读取下一行
        }
        reader.close()
        `is`.close()
    }


    @Throws(IOException::class)
    fun readFile(filePath: String): String {
        val sb = StringBuffer()
        readToBuffer(sb, filePath)
        return sb.toString()
    }
}